package kyssion.leetcode.num201_250;

public class code224_基本计算器 {
    private int index;
    private int length;

    public static void main(String[] args) {
        System.out.println(new code224_基本计算器().calculate("(1+(4+5+2)-3)+(6+8)"));
    }

    /**
     * 基本递归方法,速度很快
     * @param s
     * @return
     */
    public int calculate(String s) {
        char[] item = s.toCharArray();
        index = 0;
        length = item.length;
        return ans(item);
    }

    private int ans(char[] item) {
        int nowNum = 0;
        int beforeIndex = -1;
        while (index < length) {
            if(item[index]==' '){
                index++;
                continue;
            }
            if (item[index] == '+') {
                beforeIndex = 1;
                index++;
            } else if (item[index] == '-') {
                beforeIndex = 2;
                index++;
            } else if (item[index] == '(') {
                index++;
                int other = ans(item);
                if (beforeIndex == -1) {
                    nowNum = other;
                } else if (beforeIndex == 1) {
                    nowNum += other;
                } else {
                    nowNum -= other;
                }
                beforeIndex = -1;
            } else if (item[index] == ')') {
                index++;
                return nowNum;
            } else if (item[index] >= '0' && item[index] <= '9') {
                int other = 0;
                while (index < length && item[index] >= '0' && item[index] <= '9') {
                    other = other * 10 + item[index] - '0';
                    index++;
                }
                if (beforeIndex == -1) {
                    nowNum = other;
                } else if (beforeIndex == 1) {
                    nowNum += other;
                } else {
                    nowNum -= other;
                }
                beforeIndex = -1;
            }
        }
        return nowNum;
    }
}
